package com.xiaobing.user.controller;

import com.xiaobing.common.base.BaseController;
import com.xiaobing.common.entity.system.SysDept;
import com.xiaobing.common.entity.system.SysRole;
import com.xiaobing.common.entity.system.SysUser;
import com.xiaobing.common.entity.system.relation.SysUserRole;
import com.xiaobing.common.povo.LoginUser;
import com.xiaobing.common.res.Result;
import com.xiaobing.common.token.TokenService;
import com.xiaobing.common.utils.StringUtils;
import com.xiaobing.user.service.ISysDeptService;
import com.xiaobing.user.service.ISysPermissionMenuService;
import com.xiaobing.user.service.ISysRoleService;
import com.xiaobing.user.service.ISysUserService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 角色信息
 *
 * @author xulk
 */
@Tag(name = "角色管理")
@RestController
@RequestMapping("/user/role")
public class SysRoleController extends BaseController {
    @Resource
    private ISysRoleService roleService;

    @Resource
    private TokenService tokenService;

    @Resource
    private ISysPermissionMenuService permissionService;

    @Resource
    private ISysUserService userService;

    @Resource
    private ISysDeptService deptService;


    @Operation(summary = "角色列表")
    @GetMapping("/list")
    public Result list(@RequestBody(required = false) SysRole role) {
        List<SysRole> list = roleService.selectRoleList(role);
        return Result.success(list);
    }


    /**
     * 根据角色编号获取详细信息
     */

    @GetMapping(value = "/{roleId}")
    public Result getInfo(@PathVariable Long roleId) {
        roleService.checkRoleDataScope(roleId);
        return success(roleService.selectRoleById(roleId));
    }

    /**
     * 新增角色
     */

    @PostMapping
    public Result add(@Validated @RequestBody SysRole role) {
        if (!roleService.checkRoleNameUnique(role)) {
            return error("新增角色'" + role.getRoleName() + "'失败，角色名称已存在");
        } else if (!roleService.checkRoleKeyUnique(role)) {
            return error("新增角色'" + role.getRoleName() + "'失败，角色权限已存在");
        }
        role.setCreateBy(getUsername());
        return Result.success(roleService.insertRole(role));

    }

    /**
     * 修改保存角色
     */

    @PutMapping
    public Result edit(@Validated @RequestBody SysRole role) {
        roleService.checkRoleAllowed(role);
        roleService.checkRoleDataScope(role.getId());
        if (!roleService.checkRoleNameUnique(role)) {
            return error("修改角色'" + role.getRoleName() + "'失败，角色名称已存在");
        } else if (!roleService.checkRoleKeyUnique(role)) {
            return error("修改角色'" + role.getRoleName() + "'失败，角色权限已存在");
        }
        role.setUpdateBy(getUsername());

        if (roleService.updateRole(role) > 0) {
            // 更新缓存用户权限
            LoginUser loginUser = getLoginUser();
            if (StringUtils.isNotNull(loginUser.getSysUser()) && !loginUser.getSysUser().isAdmin()) {
                loginUser.setSysUser(userService.selectUserByUserName(loginUser.getSysUser().getUserName()));
                tokenService.setLoginUser(loginUser);
            }
            return Result.success();
        }
        return Result.error("修改角色'" + role.getRoleName() + "'失败，请联系管理员");
    }

    /**
     * 修改保存数据权限
     */

    @PutMapping("/dataScope")
    public Result dataScope(@RequestBody SysRole role) {
        roleService.checkRoleAllowed(role);
        roleService.checkRoleDataScope(role.getId());
        return Result.success(roleService.authDataScope(role));
    }

    /**
     * 状态修改
     */

    @PutMapping("/changeStatus")
    public Result changeStatus(@RequestBody SysRole role) {
        roleService.checkRoleAllowed(role);
        roleService.checkRoleDataScope(role.getId());
        role.setUpdateBy(getUsername());
        return Result.success(roleService.updateRoleStatus(role));
    }

    /**
     * 删除角色
     */

    @DeleteMapping("/{roleIds}")
    public Result remove(@PathVariable Long[] roleIds) {
        return Result.success(roleService.deleteRoleByIds(roleIds));
    }

    /**
     * 获取角色选择框列表
     */

    @GetMapping("/optionselect")
    public Result optionselect() {
        return success(roleService.selectRoleAll());
    }

    /**
     * 查询已分配用户角色列表
     */

    @GetMapping("/authUser/allocatedList")
    public Result allocatedList(SysUser user) {
        List<SysUser> list = userService.selectAllocatedList(user);
        return Result.success(list);
    }

    /**
     * 查询未分配用户角色列表
     */
    @GetMapping("/authUser/unallocatedList")
    public Result unallocatedList(SysUser user) {
        List<SysUser> list = userService.selectUnallocatedList(user);
        return Result.success(list);
    }

    /**
     * 取消授权用户
     */
    @PutMapping("/authUser/cancel")
    public Result cancelAuthUser(@RequestBody SysUserRole userRole) {
        return Result.success(roleService.deleteAuthUser(userRole));
    }

    /**
     * 批量取消授权用户
     */
    @PutMapping("/authUser/cancelAll")
    public Result cancelAuthUserAll(Long roleId, Long[] userIds) {
        return Result.success(roleService.deleteAuthUsers(roleId, userIds));
    }

    /**
     * 批量选择用户授权
     */
    @PutMapping("/authUser/selectAll")
    public Result selectAuthUserAll(Long roleId, Long[] userIds) {
        roleService.checkRoleDataScope(roleId);
        return Result.success(roleService.insertAuthUsers(roleId, userIds));
    }

    /**
     * 获取对应角色部门树列表
     */
    @GetMapping(value = "/deptTree/{roleId}")
    public Result deptTree(@PathVariable("roleId") Long roleId) {
        Map<String, Object> ajax = new HashMap<>();
        ajax.put("checkedKeys", deptService.selectDeptListByRoleId(roleId));
        ajax.put("depts", deptService.selectDeptToTree(new SysDept()));
        return Result.success(ajax);
    }
}
